import React, { Component } from "react";
import { Button, Icon, message, Popover } from "antd";
import Info from "components/info";
import { connect } from "react-redux";
import { messages } from "share/common";
import menuRoute from "routes/menuRoute";
import Condition from "components/condition";
import SlideFrame from "components/slide-frame";
import AdvancedTable from "components/advanced-table";
import {
  invoiceCheckGetServiceMap,
  invoiceCheckDeleteServiceMap,
} from "containers/supplier-management/invoice-management/dataSources";
import { tableDecorator } from "./decorator";
import InvoiceCheckForm from "./invoice-check-form";
import "styles/request-and-expense-settings/invoice-check.scss";
import invoiceManagementService from "./invoice-management.service";
import priceTaxRuleService from "../price-tax-seperation-rule/price-tax-seperation-service";
import { batchOperations } from "components/template/wrapped-table-params/batch-operations";
import settingService from "../request-and-expense-settings.service";
import JumpConfigCenter from "../../setting/configuration-center/jump-config-center";
import Space from "components/space";

const { SimpleTable } = AdvancedTable;
const { If } = Condition;

@tableDecorator
class InvoiceCheck extends Component {
  constructor(props) {
    super(props);
    this.modeRef = null;
    this.state = {
      columns: ["companyNameList", "operation"],
      searchColumns: ["companyNameList"],
      invoiceControlDetail: menuRoute.getRouteItem(
        "invoice-controls-detail",
        "key"
      ),
    };
  }

  handleRowClick = async (record) => {
    const {
      receiptCheckOptId,
      receiptToInvoiceOptId,
      receiptDisplayOptId,
      separationInvoiceOptId,
    } = record;
    const { tab } = this.props;
    const funcObj = {
      "invoice-to-cost": async () => {
        this.setState({ loading: true });
        try {
          const ret = await invoiceManagementService.getInvoiceToCostDetail(
            receiptToInvoiceOptId
          );
          this.handleNew(ret.data);
        } catch (e) {}
        this.setState({ loading: false });
      },
      "invoice-check": () => {
        this.context.router.push(
          `/main/supplier/invoice-management-control/detail/${receiptCheckOptId}`
        );
      },
      "invoice-controls": () => {
        this.context.router.push(
          this.state.invoiceControlDetail.url.replace(
            ":id",
            receiptDisplayOptId
          )
        );
      },
      "price-tax": async () => {
        this.setState({ loading: true });
        try {
          const ret = await priceTaxRuleService.getSeparationdetails(
            separationInvoiceOptId
          );
          this.handleNew(ret.data);
        } catch (e) {}
        this.setState({ loading: false });
      },
    };
    funcObj[tab]();
  };

  handleNew = (record) => {
    const { tenant, tab } = this.props;
    SlideFrame.open(
      {
        title: messages("common.create") /*新建*/,
        content: InvoiceCheckForm,
        afterClose: this.afterCloseSlideFrame,
        params: {
          tenant,
          tab,
          ...record,
        },
      },
      this
    );
  };

  handleDelete = async (record) => {
    const {
      receiptCheckOptId,
      receiptToInvoiceOptId,
      receiptDisplayOptId,
      separationInvoiceOptId,
    } = record;
    this.setState({ loading: true });
    try {
      await invoiceCheckDeleteServiceMap.get(this.props.tab)(
        receiptCheckOptId ||
          receiptToInvoiceOptId ||
          receiptDisplayOptId ||
          separationInvoiceOptId
      );
      message.success(messages("common.delete.successful") /*删除成功*/);
      this.modeRef.getList();
    } catch (e) {}
    this.setState({ loading: false });
  };

  afterCloseSlideFrame = (flag) => {
    flag && this.modeRef.getList();
  };

  service = (page, size, searchParams) =>
    invoiceCheckGetServiceMap.get(this.props.tab)({
      page,
      size,
      ...searchParams,
    });

  renderDefaultRules = () => {
    const defaultRules = [
      messages("expense-3.key176") /*优先级从高到低分别为：*/,
      messages(
        "expense-3.key177"
      ) /*1.发票不重复／重复未知、且发票状态=正常、且返回001-查验成功，可生成费用*/,
      messages(
        "expense-3.key178"
      ) /*2.发票不重复／重复未知、且发票状态=正常、且返回10023-抬头不存在，可生成费用*/,
      messages(
        "expense-3.key179"
      ) /*3.发票查验返回码包含【只能查验次日发票】，可生成费用*/,
    ];
    return (
      <section>
        {defaultRules.map((item) => (
          <p>{item}</p>
        ))}
      </section>
    );
  };

  render() {
    const { loading } = this.state;
    const { tab, children } = this.props;
    const {
      info: { dataSource, attributes },
    } = this.handleLevelMessage(tab);
    const { columns, searchColumns } = this.handleLevelMessage(tab);
    const rowKey = {
      "invoice-check": "receiptCheckOptId",
      "invoice-to-cost": "receiptToInvoiceOptId",
      "invoice-controls": "receiptDisplayOptId",
      "price-tax": "separationInvoiceOptId",
    };
    const serviceList = {
      "invoice-check": settingService.batchDeleteInvoiceCheck,
      "invoice-to-cost": settingService.batchDeleteInvoiceToCost,
      "invoice-controls": settingService.batchDeleteInvoiceControls,
      "price-tax": settingService.batchDeleteSeparationInvoice,
    };
    const tableParams =
      tab === "invoice-check"
        ? {}
        : batchOperations(
            {
              rowKey: rowKey[tab],
            },
            [
              {
                type: "DELETE",
                service: serviceList[tab],
                onOk: () => this.modeRef.getList(),
              },
            ],
            this
          );

    return (
      <section className="invoice-check">
        <SimpleTable
          showUtils
          tableName={`invoice-check-table.${tab}`}
          show={["tag-list", "table-utils"]}
          onRef={(ref) => (this.modeRef = ref)}
          onRow={(record) => ({ onClick: () => this.handleRowClick(record) })}
          rowKey={rowKey[tab]}
          loading={loading}
          columns={this.handleColumns(columns)}
          service={this.service}
          searchForm={this.handleSearchForm(searchColumns)}
          {...tableParams}
        >
          {children}
          <Space direction="vertical" size="small">
            <Info paragraph dataSource={dataSource} attributes={attributes} />
            {["invoice-to-cost", "invoice-controls"].includes(tab) && (
              <JumpConfigCenter tab={tab} />
            )}
          </Space>
          <Button
            style={{ marginTop: "12px" }}
            type="primary"
            onClick={() => this.handleNew()}
          >
            {messages("common.create") /*新建*/}
          </Button>

          {tab === "invoice-to-cost" && (
            <a style={{ float: "right" }}>
              <Popover placement="topLeft" content={this.renderDefaultRules()}>
                <Icon type="file-text" />{" "}
                {messages("expense-3.key180") /*默认规则*/}
              </Popover>
            </a>
          )}
        </SimpleTable>
      </section>
    );
  }
}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
  };
}

InvoiceCheck.contextTypes = {
  router: React.PropTypes.object,
};

InvoiceCheck.propTypes = {
  tab: React.PropTypes.string,
};

export default connect(mapStateToProps)(InvoiceCheck);
